package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public String createOrder(CreateOrderRequest request) {
        // CreateOrderResponse response = new CreateOrderResponse();
        // try{
        //
        // }catch (Exception e){
        //     log.error("OrderCoreServiceImpl.createOrder Occur Exception :"+e);
        //
        // }
        //创建pipeline对象
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Override
    @Transactional
    public void cancelOrder(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setStatus(7);
        order.setCloseTime(new Date());
        int effected = orderMapper.updateByPrimaryKey(order);
        if (effected<0){
            throw new BizException(OrderRetCode.ORDER_CANCEL_FAIL.getCode(),
                    OrderRetCode.ORDER_CANCEL_FAIL.getMessage());
        }
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        orderItemMapper.updateStockStatus(2,orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItems) {
            Stock stock = stockMapper.selectStock(orderItem.getItemId());
            stock.setStockCount((long)orderItem.getNum());
            stock.setLockCount(-orderItem.getNum());
            stockMapper.updateStock(stock);
        }
    }

    @Override
    @Transactional
    public void deleteOrder(String orderId) {
        Example example2 = new Example(OrderItem.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example2);
        for (OrderItem orderItem : orderItems) {
            if (orderItem.getStatus()==1){
                Stock stock = stockMapper.selectStock(orderItem.getItemId());
                stock.setStockCount((long)orderItem.getNum());
                stock.setLockCount(-orderItem.getNum());
                stockMapper.updateStock(stock);
            }
        }


        int effected = orderMapper.deleteByPrimaryKey(orderId);
        if (effected<0){
            throw new BizException(OrderRetCode.ORDER_DELETE_FAIL.getCode(),
                    OrderRetCode.ORDER_DELETE_FAIL.getMessage());
        }
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        int effected2 = orderItemMapper.deleteByExample(example);
        if (effected2<0){
            throw new BizException(OrderRetCode.ORDER_DELETE_FAIL.getCode(),
                    OrderRetCode.ORDER_DELETE_FAIL.getMessage());
        }
        int effected3 = orderShippingMapper.deleteByPrimaryKey(orderId);
        if (effected3<0){
            throw new BizException(OrderRetCode.ORDER_DELETE_FAIL.getCode(),
                    OrderRetCode.ORDER_DELETE_FAIL.getMessage());
        }
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
